package com.zm.rpc.server.channel.handler;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zm.rpc.protocol.RpcProtocol;
import com.zm.rpc.protocol.enums.RequestType;
import com.zm.rpc.server.dispatcher.IDispatcher;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@Component
 @Sharable
public class RpcHandler extends SimpleChannelInboundHandler<RpcProtocol<Object>>{
    private static final Logger log = Logger.getLogger(RpcHandler.class);

    @Autowired
    private IDispatcher dispatcher;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcProtocol<Object> protocol) throws Exception {
        Object result = dispatcher.execute(protocol);
        protocol.setContext(result);
        protocol.getHeader().setReqType(RequestType.RESPONSE.code());
        ctx.writeAndFlush(protocol);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("error!!!",cause);
    }
    
}
